package com.kidala.tool;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.Converter;

public class CharactersConverter {

    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "To jest tekst do przekonwertowania - zlecenia bieżąćę ążźćńłóśę";
        ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
        convertUtilsBean.deregister(String.class);
        convertUtilsBean.register(new PolishCharsConverter(), String.class);

        System.out.println(convertUtilsBean.convert(str));
        System.out.println(URLEncoder.encode(str, "US-ASCII"));
    }

    static class PolishCharsConverter implements Converter {
        private Map<String, String> charsMapping;
        {
            charsMapping = new HashMap<String, String>();
            charsMapping.put("\\s", "_");
            charsMapping.put("ą", "a");
            charsMapping.put("ć", "c");
            charsMapping.put("ę", "e");
            charsMapping.put("ó", "o");
            charsMapping.put("ł", "l");
            charsMapping.put("ń", "n");
            charsMapping.put("ś", "s");
            charsMapping.put("ź", "z");
            charsMapping.put("ż", "z");

            charsMapping.put("Ą", "A");
            charsMapping.put("Ć", "C");
            charsMapping.put("Ę", "E");
            charsMapping.put("Ó", "O");
            charsMapping.put("Ł", "L");
            charsMapping.put("Ń", "N");
            charsMapping.put("Ś", "S");
            charsMapping.put("Ź", "Z");
            charsMapping.put("Ż", "Z");
        }

        public Object convert(Class type, Object value) {
            if (value == null) {
                return (String) null;
            } else {
                String result = value.toString();
                Set<Entry<String, String>> entrySet = charsMapping.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    result = result.replaceAll(entry.getKey(), entry.getValue());
                }
                return result;
            }
        }
    }
}
